import { CrudOptions, AddReq, DelReq, EditReq, dict, CrudExpose, UserPageQuery, CreateCrudOptionsRet } from '@fast-crud/fast-crud';
import * as api from './api';
import { auth } from "/@/utils/authFunction";
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';

interface RowData {
    id: string;
    status: string;
}

export default function ({ crudExpose }: { crudExpose: CrudExpose }): CreateCrudOptionsRet {
    const pageRequest = async (query: any) => {
        return await api.GetList(query);
    };
    const editRequest = async ({ form, row }: EditReq) => {
        if (row.id) {
            form.id = row.id;
        }
        return await api.UpdateObj(form);
    };
    const delRequest = async ({ row }: DelReq) => {
        return await api.DelObj(row.id);
    };
    const addRequest = async ({ form }: AddReq) => {
        return await api.AddObj(form);
    };

    const exportRequest = async (query: UserPageQuery) => {
        return await api.exportData(query);
    };

    return {
        crudOptions: {
            request: {
                pageRequest,
                addRequest,
                editRequest,
                delRequest,
            },
            actionbar: {
                buttons: {
                    add: {
                        text: "新增",
                        type: "primary",
                        icon: "plus",
                        show: auth('SalesStrategyModelViewSet:Create'),
                    },
                    export: {
                        text: "导出",
                        type: "warning",
                        icon: "download",
                        show: auth('SalesStrategyModelViewSet:Export'),
                        click() {
                            return exportRequest(crudExpose.getSearchFormData());
                        }
                    },
                }
            },
            table: {
                border: true,
                stripe: true,
                highlight: true,
            },
            search: {
                show: true,
                buttons: {
                    search: {
                        text: "搜索",
                        icon: "search",
                        show: auth('SalesStrategyModelViewSet:Search')
                    },
                    reset: {
                        text: "重置",
                        icon: "refresh-right"
                    }
                }
            },
            rowHandle: {
                fixed: 'right',
                width: 260,
                dropdown: {
                    more: {
                        text: '更多'
                    }
                },
                buttons: {
                    view: {
                        type: 'primary',
                        text: '查看',
                        icon: 'view',
                        order: 1,
                        show: auth('SalesStrategyModelViewSet:Retrieve')
                    },
                    edit: {
                        type: 'warning',
                        text: '编辑',
                        icon: 'edit',
                        order: 2,
                        show: auth('SalesStrategyModelViewSet:Update')
                    },
                    approve: {
                        type: 'success',
                        text: '通过',
                        icon: 'check',
                        order: 3,
                        show: ({ row }: { row: RowData }) => {
                            return auth('SalesStrategyModelViewSet:Update') && row.status === 'pending';
                        },
                        click: async ({ row }: { row: RowData }) => {
                            try {
                                await api.updateStatus(row.id, 'approved');
                                ElMessage.success('审批通过成功');
                                crudExpose.doRefresh();
                            } catch (error) {
                                console.error('审批失败:', error);
                                ElMessage.error('审批失败');
                            }
                        }
                    },
                    reject: {
                        type: 'danger',
                        text: '驳回',
                        icon: 'close',
                        order: 4,
                        show: ({ row }: { row: RowData }) => {
                            return auth('SalesStrategyModelViewSet:Update') && row.status === 'pending';
                        },
                        click: async ({ row }: { row: RowData }) => {
                            try {
                                await api.updateStatus(row.id, 'rejected');
                                ElMessage.success('驳回成功');
                                crudExpose.doRefresh();
                            } catch (error) {
                                console.error('驳回失败:', error);
                                ElMessage.error('驳回失败');
                            }
                        }
                    },
                    remove: {
                        type: 'danger',
                        text: '删除',
                        icon: 'delete',
                        order: 5,
                        show: auth('SalesStrategyModelViewSet:Delete')
                    },
                },
            },
            columns: {
                name: {
                    title: '策略名称',
                    type: 'input',
                    search: { show: true },
                    column: {
                        minWidth: 120,
                        sortable: 'custom',
                    },
                    form: {
                        rules: [{ required: true, message: '策略名称必填' }],
                        component: {
                            placeholder: '请输入策略名称',
                        },
                    },
                },
                description: {
                    title: '策略描述',
                    type: 'textarea',
                    search: { show: false },
                    column: {
                        minWidth: 200,
                    },
                    form: {
                        rules: [{ required: true, message: '策略描述必填' }],
                        component: {
                            placeholder: '请输入策略描述',
                            span: 24,
                        },
                    },
                },
                start_date: {
                    title: '开始日期',
                    type: 'date',
                    search: { show: true },
                    form: {
                        rules: [{ required: true, message: '开始日期必填' }],
                        component: {
                            format: "YYYY-MM-DD",
                            valueFormat: "YYYY-MM-DD",
                            placeholder: '请选择开始日期',
                            onChange: (value: string) => {
                                const form = crudExpose.getFormData();
                                if (form.end_date && dayjs(value).isAfter(form.end_date)) {
                                    ElMessage.warning('开始日期不能晚于结束日期');
                                    form.start_date = '';
                                }
                            }
                        }
                    },
                    column: {
                        align: "center",
                        width: 120,
                        component: { name: "fs-date-format", format: "YYYY-MM-DD" }
                    }
                },
                end_date: {
                    title: '结束日期',
                    type: 'date',
                    search: { show: true },
                    form: {
                        rules: [
                            { required: true, message: '结束日期必填' },
                            {
                                validator: (rule: any, value: string) => {
                                    const form = crudExpose.getFormData();
                                    if (form.start_date && value && dayjs(value).isBefore(form.start_date)) {
                                        return Promise.reject('结束日期不能早于开始日期');
                                    }
                                    return Promise.resolve();
                                }
                            }
                        ],
                        component: {
                            format: "YYYY-MM-DD",
                            valueFormat: "YYYY-MM-DD",
                            placeholder: '请选择结束日期',
                            onChange: (value: string) => {
                                const form = crudExpose.getFormData();
                                if (form.start_date && dayjs(value).isBefore(form.start_date)) {
                                    ElMessage.warning('结束日期不能早于开始日期');
                                    form.end_date = '';
                                }
                            }
                        }
                    },
                    column: {
                        align: "center",
                        width: 120,
                        component: { name: "fs-date-format", format: "YYYY-MM-DD" }
                    }
                },
                status: {
                    title: '状态',
                    type: 'dict-select',
                    search: { show: true },
                    dict: dict({
                        data: [
                            { value: 'pending', label: '待审批' },
                            { value: 'approved', label: '已通过' },
                            { value: 'rejected', label: '已驳回' },
                            { value: 'cancelled', label: '已取消' }
                        ]
                    }),
                    column: {
                        width: 100,
                        sortable: 'custom',
                        align: 'center',
                        formatter: ({ row }: { row: RowData }) => {
                            const statusMap: Record<string, { text: string; type: string }> = {
                                pending: { text: '待审批', type: 'warning' },
                                approved: { text: '已通过', type: 'success' },
                                rejected: { text: '已驳回', type: 'danger' },
                                cancelled: { text: '已取消', type: 'info' }
                            };
                            const status = statusMap[row.status] || { text: row.status, type: 'info' };
                            return <el-tag size="small" type={status.type}>{status.text}</el-tag>;
                        }
                    },
                    form: {
                        show: false,
                        value: 'pending'
                    }
                },
            },
        },
    };
} 